import type { Store } from 'antd/es/form/interface';
import _ from 'lodash';

function formDataToArr(
  obj: Store,
  tableData: any[],
  key?: string,
  otherParams?: Store,
  format?: Record<string, (data: any) => Store>,
): any[] {
  const arr: any[] = [];
  const idKey = key ? key : 'id';

  for (let i = 0; i < tableData.length; i++) {
    const row = tableData[i];
    const idValue = row[idKey];
    let item: any = { ...row };
    if (otherParams) {
      item = { ...otherParams };
    }
    for (const o in obj) {
      if (o.indexOf('@') > -1) {
        const currentId = o.split('@')[1];
        if (currentId == idValue) {
          const currentKey = o.split('@')[0];
          if (format && format[currentKey]) {
            const formatData = format[currentKey](obj[o]);
            item = _.merge(item, formatData);
          } else {
            item[currentKey] = obj[o];
          }
        }
      }
    }
    arr.push(item);
  }
  return arr;
}

function arrToFormData(
  tableData: any[],
  key?: string,
  keyRange?: string[],
  transform?: Record<string, (data: any) => any>,
): Store {
  const obj: Store = {};
  for (let i = 0; i < tableData.length; i++) {
    const row: any = tableData[i];
    const idKey: any = key ? key : 'id';

    for (const r in row) {
      const newKey = `${r}@${row[idKey]}`;
      const tdData = transform && _.isFunction(transform[r]) ? transform[r](row[r]) : row[r];
      if (keyRange && keyRange.length > 0) {
        if (keyRange.indexOf(r) > -1) {
          obj[newKey] = tdData;
        }
      } else {
        obj[newKey] = tdData;
      }
    }
  }
  return obj;
}

export { formDataToArr, arrToFormData };
